package com.usian.filter;

import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.filter.OrderedFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;

import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @TODO:
 * @Author:baimu
 * @Date:2023 12 04 09 58
 **/
@Component
@Slf4j
@Order(1)
public class MyFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        log.info("=======MyFilter=========");
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        log.info("requeset url:{}",path);

        if(path.contains("v1/user/login")){

            log.info("当前是登陆请求");
            return chain.filter(exchange);
        }

        String token = request.getHeaders().getFirst("token");
        log.info("token:{}",token);

        //token为空
        if(StringUtils.isEmpty(token)){
            //返回401 状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();

        }
        //2种情况，代表验证不通过
        //1：token过期
        //2:token 格式不正确，抛异常

        try{
            boolean verify = JWTUtil.verify(token, "111".getBytes());
            //验证通过
            if(verify){
                return chain.filter(exchange);
            } else {
                //返回401 状态码
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }catch (Exception e){
            e.printStackTrace();
            //返回401 状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }



      //  return chain.filter(exchange);
    }

//    @Override
//    public int getOrder() {
//        return 2;
//    }
}
